package com.myjob.handlerImpl;

import com.myjob.config.CompanyProperties;
import com.myjob.config.Constants;
import com.myjob.enums.RedisEnums;
import com.myjob.exception.OptionException;
import com.myjob.utils.RedisUtil;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author chenyuan
 * @date 2021/3/2 21:03
 */
@Service
@Slf4j
public class UploadHandlerImpl {
	@Autowired
	private CompanyProperties companyProperties;
	@Autowired
	private RedisUtil redisUtil;

	//支持的图片类型
	private static final List<String> CONTENT_TYPE = Arrays.asList("image/gif", "image/jpeg", "image/png");

	public String uploadImage(MultipartFile file, String logoPrefix, String userId) {
		String result = "";
		// 获取原始的文件名
		String originalFilename = file.getOriginalFilename();

		try {
			//建议文件类型
			String contentType = file.getContentType();
			if (!CONTENT_TYPE.contains(contentType)) {
				result = "文件类型不合法";
				log.info(result);
				return result;
			}
			//检验文件内容
			BufferedImage read = ImageIO.read(file.getInputStream());
			if (read == null) {
				result = "文件内容不合法";
				log.info(result);
				return result;
			}
			// 修改文件名称
			if (UtilValidate.isNotEmpty(userId)) {
				originalFilename = logoPrefix + userId + ".png";
			}else {
				originalFilename = logoPrefix + "default" + ".png";
			}
			//保存文件
			file.transferTo(new File(companyProperties.getPrefixPath()+ companyProperties.getPackageName() + originalFilename));

			String imagePath = "http://"+ companyProperties.getServerPath() +"/"+ companyProperties.getPackageName() +originalFilename;
			// 将文件图片地址存入 Redis ，设置过期时间为 1 天
			redisUtil.set(originalFilename, imagePath, 1, TimeUnit.DAYS);
			result = "企业 Logo 上传成功，地址为:" + imagePath;
			log.info(result + " , 并成功存入 Redis ,过期时间为：1 天");

		} catch (IOException e) {
			result = "服务器内部错误";
			log.error(result);
			e.printStackTrace();
			throw new OptionException(result);
		}

		return result;
	}
}
